package cn.bookCity.servlet;

import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bookCity.domain.Page;
import cn.bookCity.domain.Products;
import cn.bookCity.service.ProductService;
import cn.bookCity.util.BeanFactory;

@WebServlet("/book/product")
public class IndexServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public String show(HttpServletRequest request,HttpServletResponse response)throws Exception {
		int pageSize=10;
		Page page=new Page();
		String pageIndex=request.getParameter("pageIndex");
		ProductService p=(ProductService)BeanFactory.getBean("ProductService");
		int currentIndex=1;
		if(pageIndex==null) {
			currentIndex=1;
		}else {
			currentIndex=Integer.parseInt(pageIndex);
		}
		int count=p.getCount();
		int totalPages=(count%pageSize)==0?(count/pageSize):((count/pageSize)+1);
		if(currentIndex<=1) {
			currentIndex=1;
		}else if(currentIndex>=totalPages) {
			currentIndex=totalPages;
		}
		page.setTotalpages(totalPages);
		page.setCurrentIndex(currentIndex);
		int startNo=(currentIndex-1)*pageSize;
		page.setAllProducts(p.getPageProducts(startNo, pageSize));
		request.setAttribute("bookList", page);
        return "/index.jsp";		
	}
	public String search(HttpServletRequest request,HttpServletResponse response)throws Exception {
		
		String keywords=request.getParameter("keywords");
		ProductService p=(ProductService)BeanFactory.getBean("ProductService");
		List<Products> products=p.getProductByName(keywords);
		request.setAttribute("products", products);
		return "/search.jsp";
		
	}
	

}
